package com.weizhong.update.view;

import com.weizhong.update.R;
import com.weizhong.update.util.AppUpdateDetail;
import com.weizhong.update.view.HorizontalProgressBarWithNumber;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.WZAccessServiceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

public class AppUpdateActivity extends Activity {
	public TextView textView;
	private HorizontalProgressBarWithNumber mProgressBar;
	private AppUpdateDetail appUpdateDetail = null;
	private static final int MSG_PROGRESS_UPDATE = 3001;
	private static final String TAG = "MainActivity";
	private int appSize;
	private Activity mActivity = this;
	private final String UPDATE_DIR = "wz_app_update.info";

	//进度条更新时间(毫秒)
	private int process_time = 8000;
	//进度条更新间隔时间()
	private static int bar_update_time = 0;
	//屏幕常亮锁
	WakeLock m_wklk;

	//更新进度条
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Log.i(TAG,"handleMessage");
			int progress = mProgressBar.getProgress();
			if(appUpdateDetail == null){
				Log.d("MainActivity", "appUpdateDetail do nothing");
				progress = 100;
				appSize = 0;
			}else {
				appSize = appUpdateDetail.getAppSize();
				process_time = 8000 * appSize;
				//限制，最多不超过100sec
				if(process_time > 10000 * 10){
					process_time = 100000;
				}
				bar_update_time = process_time/100;
			}
			
			if(appSize == 0){
				progress = 100;
			}else {
				progress += 1;
			}
			Log.i(TAG,"handleMessage process is: " + progress);
			mProgressBar.setProgress(progress);
			if(progress >= 90){
				if(appUpdateDetail == null){
					appUpdateDetail = new AppUpdateDetail(getApplicationContext());
				}
				if(appUpdateDetail.isAppUpdateSuccess()){
					Log.i(TAG, "更新应用成功!");
					if(appUpdateDetail != null){
						appUpdateDetail.setUpdateTime(Long.valueOf(appUpdateDetail.getLastUpdateTime()));
						appUpdateDetail.clear();
					}
					SharedPreferences sharedPreferences = getApplicationContext().
							getSharedPreferences("user", Context.MODE_PRIVATE);
					Editor editor=sharedPreferences.edit();
					editor.putLong("lastFailTime", -1);
					editor.putInt("tryTimes", -1);
					editor.commit();
				}else{
					Log.i(TAG,"更新应用失败.");
					//一次更新，如果尝试更新失败 >= 三次，则强制跳过此次更新
					SharedPreferences sharedPreferences = getApplicationContext().
							getSharedPreferences("user", Context.MODE_PRIVATE);
					int tryTimes = sharedPreferences.getInt("tryTimes", -1);
					long lastFailTime = sharedPreferences.getLong("lastFailTime", -1);
					
					if (lastFailTime == -1){
						//This is first fail time for appUpdateDetail.getLastUpdateTime()
						Editor editor = sharedPreferences.edit();
						editor.putLong("lastFailTime", Long.valueOf(appUpdateDetail.getLastUpdateTime()));
						editor.putInt("tryTimes", 1);
						editor.commit();
					}else if (lastFailTime == Long.valueOf(appUpdateDetail.getLastUpdateTime())) {
						//尝试超过三次，则强制跳过此次更新
						if(tryTimes >= 3){
							appUpdateDetail.setUpdateTime(Long.valueOf(appUpdateDetail.getLastUpdateTime()));
							appUpdateDetail.clear();
							Editor editor=sharedPreferences.edit();
							editor.putLong("lastFailTime", -1);
							editor.putInt("tryTimes", -1);
							editor.commit();
						}else {
							tryTimes += 1;
							Editor editor=sharedPreferences.edit();
							editor.putInt("tryTimes", tryTimes);
							editor.commit();
						}
					}else {
						appUpdateDetail.setUpdateTime(Long.valueOf(appUpdateDetail.getLastUpdateTime()));
						appUpdateDetail.clear();
						Editor editor=sharedPreferences.edit();
						editor.putLong("lastFailTime", -1);
						editor.putInt("tryTimes", -1);
						editor.commit();
					}					
				}
			}

			if (progress >= 100) {
				mHandler.removeMessages(MSG_PROGRESS_UPDATE);
				textView.setText("更新应用成功");
				WZAccessServiceManager.writeSystemShareFile(UPDATE_DIR, "noupdate", "");
				
				new Thread(){
					public void run() {
						super.run();
						try {
							sleep(3000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						if(appUpdateDetail != null){
							mActivity.finish();
							appUpdateDetail.startSystemUi();
						}else {
							appUpdateDetail = new AppUpdateDetail(getApplicationContext());
							mActivity.finish();
							appUpdateDetail.startSystemUi();
						}
					};
				}.start();

			}
			if(progress < 100){
				mHandler.sendEmptyMessageDelayed(MSG_PROGRESS_UPDATE, bar_update_time);
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		Log.i(TAG,"onCreate(Bundle bundle)");
		getWindow().getDecorView().setSystemUiVisibility(View.GONE);
		setContentView(R.layout.update_processbar);
		mProgressBar = (HorizontalProgressBarWithNumber) findViewById(R.id.id_progressbar);

		if(appUpdateDetail == null){
			appUpdateDetail = new AppUpdateDetail(getApplicationContext());
			appSize = appUpdateDetail.getAppSize();
			process_time = 8000 * appSize;
			//限制，最多不超过100sec
			if(process_time > 10000 * 10){
				process_time = 100000;
			}
			bar_update_time = process_time/100;
		}

		mHandler.sendEmptyMessage(MSG_PROGRESS_UPDATE);
		textView = (TextView) findViewById(R.id.id_tv);
		textView.setText("正在更新应用，请稍候...");
		appUpdateDetail.updateApp();
		
		PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
		m_wklk = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "cn");
		m_wklk.setReferenceCounted(false);
		m_wklk.acquire();//获取常亮锁
		if(!WZAccessServiceManager.getSystemUpdateState()){
			WZAccessServiceManager.setSystemUpdateState(true);
		}
	}
	
	/**
	 * 屏蔽按键
	 */
	@Override
	public boolean onKeyDown(int arg0, KeyEvent arg1) {
		Log.i(TAG, "onKeyDown");
		return true;
	}
	
	/**
	 * 屏蔽返回键
	 */
	@Override
	public void onBackPressed() {
		Log.i(TAG, "onBackPressed");
		return;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if(m_wklk != null){
			m_wklk.release(); //释放常亮锁	
		}
	}
	
	@Override
	protected void onDestroy() {
		if(WZAccessServiceManager.getSystemUpdateState()){
			WZAccessServiceManager.setSystemUpdateState(false);
		}
		if(m_wklk != null){
			m_wklk.release(); //释放常亮锁
		}
		super.onDestroy();
	}
}
